from flask import render_template, safe_join, send_file, request

from flask_login import login_required
from redash import settings
from redash.handlers import routes
from redash.handlers.authentication import base_href
from redash.handlers.base import org_scoped_rule
from redash.security import csp_allows_embeding
from redash import settings


def add_cors_headers(headers):
    if "Origin" in request.headers:
        origin = request.headers["Origin"]

        if set(["*", origin]) & settings.ACCESS_CONTROL_ALLOW_ORIGIN:
            headers["Access-Control-Allow-Origin"] = origin
            headers["Access-Control-Allow-Credentials"] = str(
                settings.ACCESS_CONTROL_ALLOW_CREDENTIALS
            ).lower()

            if settings.ACCESS_CONTROL_REQUEST_METHOD:
                headers[
                    "Access-Control-Request-Method"
                ] = settings.ACCESS_CONTROL_REQUEST_METHOD

            if settings.ACCESS_CONTROL_ALLOW_HEADERS:
                headers[
                    "Access-Control-Allow-Headers"
                ] = settings.ACCESS_CONTROL_ALLOW_HEADERS

            headers.add("P3P","CP='CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR'")   


def render_index(isPublic = False):
    if settings.MULTI_ORG:
        response = render_template("multi_org_pub.html" if isPublic else "multi_org.html", base_href=base_href())
    else:
        full_path = safe_join(settings.STATIC_ASSETS_PATH, "index.html")
        response = send_file(full_path, **dict(cache_timeout=0, conditional=True))

    if isPublic and len(settings.ACCESS_CONTROL_ALLOW_ORIGIN) > 0:
        add_cors_headers(response.headers)

    return response


@routes.route(org_scoped_rule("/dashboard/<slug>"), methods=["GET"])
@login_required
@csp_allows_embeding
def dashboard(slug, org_slug=None):
    return render_index()


@routes.route(org_scoped_rule("/<path:path>"))
@routes.route(org_scoped_rule("/"))
@login_required
def index(**kwargs):
    return render_index()
